<template>
    <div class="page-user-discount">
        <div class="white-bg">
            <CommonNav v-model="nav" :navs="navs"></CommonNav>
        </div>

        <!-- 列表 -->
        <div class="list-wrap" v-if="usableList.length">
            <CouponCard v-for="(coupon, index) in usableList"
                :key="index"
                :coupon="coupon"
                :isSelect="isSelect"
                @click="onClickCouponCard(coupon)"
                @showPop="onShowPop(coupon)">
            </CouponCard>
        </div>

        <div v-if="unusableList && unusableList.length > 0" class="list-wrap">
            <div class="line">
                <span class="line-content">不可使用</span>
            </div>
            <CouponCard v-for="(coupon, index) in unusableList"
                :key="index"
                :coupon="coupon"
                @click="onClickUnusabledCard()"
                @showPop="onShowPop(coupon)">
            </CouponCard>
        </div>

        <!-- 列表为空 -->
        <div v-if="usableList.length == 0 && unusableList.length == 0 && !wrap.requesting" class="empty-wrap">
            <span class="icon">&#xe62c;</span>
            <div class="normal-text">没有符合的结果</div>
        </div>
        <!-- 领券规则弹窗 -->
        <div v-if="rulesPopupVisible" class="popup-container" catchtouchmove="move">
            <div class="contain-box text-center">
                <div class="inner-box">
                    <div class="title">使用规则</div>
                    <div class="rules">
                        <div class="rule">
                            可用门店：{{coupon.shop_name ? coupon.shop_name : '所有门店'}}。
                        </div>
                        <div class="rule">
                            可用类型：{{coupon.type ? (coupon.type === 'package' ? '婚纱摄影' : '实体商品') : '所有'}}。
                        </div>
                        <div class="rule">
                            抵扣规则：达到{{coupon.price_limit}}减{{coupon.money}}。
                        </div>
                        <div class="rule">
                            有效期至：{{coupon.time}}。
                        </div>
                    </div>
                </div>
                <span class="icon" @click="closePopup">&#xe80b;</span>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import CommonNav from '@/components/nav/commonNav.vue';
import CouponCard from '@/features/coupon/couponCard.vue';
import store from '@/store';
import {
    dateParse,
    dateNow,
    isUndef,
    currency,
    dateFormat,
} from '@/lib/utils';
import { EMPTY_LIST } from '@/lib/constant';

import { Component, Vue, Watch } from 'vue-property-decorator';

Component.registerHooks([
    'beforeRouteEnter',
]);

@Component({
    name: 'CouponSelect',
    components: {
        CommonNav,
        CouponCard,
    },
})
export default class CouponSelect extends Vue {
    /** 开始时间 */
    public startDateString: any = null;

    /** 结束时间 */
    public endDateString: any = null;

    /** 弹窗是否可见 */
    public popupVisible: any = false;

    /** 正在查看的popup */
    public hintCoupon: any = null;

    public nav: any = 'useable';

    public navs: any = [
        { text1: '可使用', value: 'useable' },
        { text1: '已过期', value: 'overdue' },
        { text1: '已使用', value: 'used' },
    ];

    /** 规则弹窗 */
    public rulesPopupVisible: any = false;

    /** 规则弹窗的代金券 */
    public coupon: any = null;

    public nowDate: any = null;

    /** 当前在选择状态 */
    public get isSelect() {
        return this.$route.query.isSelect === '1';
    }
    /** 当前订单价格，以分为单位 */
    public get price() {
        return this.$route.query.price;
    }
    /** 当前商品类型 */
    public get type() {
        return this.$route.query.type;
    }
    public get shopId() {
        return this.$route.query.shop_id;
    }
    public get pkgId() {
        return this.$route.query.pkg_id;
    }
    /** 代金券列表 */
    public get couponList() {
        return store.state.user.couponList;
    }

    /** 代金券数据 */
    public get couponMap() {
        return store.state.user.couponMap;
    }

    /** 代金券id */
    public get couponId() {
        return store.state.order.couponId;
    }

    /** 等待支付 */
    public get pendingCart() {
        return store.state.order.pendingCart;
    }

    public get productIds() {
        return this.pendingCart.map((item: any) => String(item.product_id));
    }

    /** 列表 */
    public get wrap() {
        return this.couponList[this.nav] || EMPTY_LIST;
    }

    /** 列表 */
    public get list() {
        return this.wrap.list.map((id: any) => this.couponMap[id]);
    }

    /** 可以使用的代金券 */
    public get usableList() {
        return this.list.filter((coupon: any) => {
            return this.checkCoupon(coupon);
        });
    }

    /** 不可使用代金券 */
    public get unusableList() {
        return this.list.filter((coupon: any) => {
            return !this.checkCoupon(coupon);
        });
    }

    @Watch('nav')
    public onNavChange(val: any) {
        this.getData(0, true);
    }

    /**
     * 获取数据
     */
    public async getData(offset: any, forceUpdate = false) {
        await store.dispatch('user/getCouponList', {
            status: this.nav,
            offset,
            count: 10,
            forceUpdate,
        });
    }

    /**
     * 检查是否可用代金券
     */
    public checkCoupon(coupon: any) {
        const matchNav = this.isSelect ? this.nav === 'useable' : true;
        const matchGood = !coupon.applicable || !this.type ? true : this.type === 'package' ? coupon.applicable.indexOf(String(this.pkgId)) !== -1 : coupon.applicable.some((item: any) => this.productIds.includes(String(item)));
        const matchShop = !coupon.shop_id || !this.shopId ? true : (Number(coupon.shop_id) === Number(this.shopId));
        const matchPrice = isUndef(this.price) || Number(coupon.price_limit) <= Number(this.price);
        const matchTime = this.nowDate.valueOf() <= dateParse(coupon.expiration_date).valueOf();
        const matchType = !coupon.type || !this.type ? true : (coupon.type === this.type);
        return matchNav && matchGood && matchShop && matchPrice && matchTime && matchType;
    }

    /**
     * 点击代金券
     */
    public onClickCouponCard(coupon: any) {
        if (this.nav !== 'useable') {
            return;
        }
        if (this.isSelect) {
            store.commit('order/setCouponId', coupon.id);
            wx.navigateBack();
        }
    }

    /**
     * 点金不可用代金券
     */
    public onClickUnusabledCard() {
        if (this.isSelect) {
            wx.showToast({
                title: '该券不可使用',
                icon: 'none',
            });
        }
    }

    /** 点击使用规则 */
    public onShowPop(coupon: any) {
        this.coupon = Object.assign(JSON.parse(JSON.stringify(coupon)), {
            price_limit: currency(coupon.price_limit),
            money: currency(coupon.money),
            time: dateFormat(dateParse(coupon.expiration_date), 'Y.M.D'),
        });
        this.rulesPopupVisible = true;
    }

    /** 隐藏使用规则 */
    public closePopup() {
        this.rulesPopupVisible = false;
    }

    public onReachBottom() {
        this.getData(this.list.length);
    }

    public async created() {
        this.nowDate = dateNow();
        this.getData(0, true);
    }
}
</script>

<style lang="less">
@import "../../lib/style/mixins.less";

.page-user-discount {
    min-height: 100%;
    background-color: #F3F3F3;
    box-sizing: border-box;

    .is-selected {
        border-bottom: 3px solid #DBA01A;
        color: #DBA01A;
    }
    .list-wrap {
        padding: 40rpx 40rpx 1rpx;
    }
    // 没有结果
    .empty-wrap {
        position: absolute;
        display: inline-block;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        color: @primary-color;
        text-align: center;
        .icon {
            font-size: 60px;
            line-height: 140rpx;
            height: 140rpx;
        }
    }

    .contain-box {
        position: absolute;
        width: 80%;
        // height: 500rpx;
        left: 10%;
        top: 50%;
        transform: translateY(-50%);
        .inner-box {
            width: 100%;
            color: #333;
            background: @white-color;
            top: 10px;
            padding: 60rpx;
            box-sizing: border-box;
            border-radius: 60rpx;
            .title {
                margin: 0 auto 40rpx;
                width: 400rpx;
                height: 80rpx;
                line-height: 80rpx;
                border-radius: 10rpx;
                font-size: 40rpx;
                color: #333;
                background: #fff;
            }
            .rules {
                font-size: 28rpx;
                text-align: left;
                counter-reset: rules start;
                .rule {
                    margin: 10rpx 0;
                    &:before {
                        content: counter(rules) "、";
                        counter-increment: rules 1;
                    }
                }
            }
        }
        .icon {
            position: relative;
            top: 60rpx;
            color: @white-color;
            font-size: 60rpx;
        }
    }
}

</style>
